# pages/base_page.py
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from utils.config import ConfigManager
from utils.logger import LogManager
import os
from datetime import datetime

class BasePage:
    def __init__(self, driver):
        self.driver = driver
        self.config = ConfigManager().locators
        self.logger = LogManager().get_logger()
        
    def find_element(self, locator_name, timeout=10):
        locator = self.config[locator_name]
        return WebDriverWait(self.driver, timeout).until(
            EC.presence_of_element_located((getattr(By, locator['by']), locator['value']))
        
    def click_element(self, locator_name, timeout=10):
        element = self.find_element(locator_name, timeout)
        self.logger.info(f"点击元素: {locator_name}")
        element.click()
        
    def input_text(self, locator_name, text, timeout=10):
        element = self.find_element(locator_name, timeout)
        self.logger.info(f"在 {locator_name} 输入文本")
        element.clear()
        element.send_keys(text)
        
    def take_screenshot(self, name):
        os.makedirs('screenshots', exist_ok=True)
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"{name}_{timestamp}.png"
        path = os.path.join('screenshots', filename)
        self.driver.save_screenshot(path)
        self.logger.info(f"截图已保存: {path}")